﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using Stacky;

namespace StackBookSvc
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        protected override void OnStop()
        {
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    Program.Log("Starting run");
                    var fbSession = new Facebook.Session.ConnectSession(ConfigurationManager.AppSettings["APIKey"], ConfigurationManager.AppSettings["Secret"]);
                    var fbApi = new Facebook.Rest.Api(fbSession);
                    StackBookLib.Interfaces.IStackBookRespository repository = new StackBookL2S.L2SStackBookRepository();
                    var accounts = repository.GetAccounts();
                    foreach (var item in accounts)
                    {
                        Program.Log(string.Format("starting {0} {1} {2}", item.FacebookId, item.StackOverflowId, item.LastUpdate));
                        if (item.StackOverflowId != null)
                        {
                            bool updateDb = false;
                            var updateTime = DateTime.Now;

                            IUrlClient urlClient = new UrlClient();
                            IProtocol protocol = new JsonProtocol();

                            var client = new StackyClient(ConfigurationManager.AppSettings["StackAppsVersion"], ConfigurationManager.AppSettings["StackAppsKey"], HostSite.StackOverflow, urlClient, protocol);
                            var questions = client.GetQuestionsByUser((int)item.StackOverflowId, QuestionsByUserSort.Activity, SortDirection.Descending, null, null, false, false, (DateTime)item.LastUpdate);
                            foreach (var question in questions)
                            {
                                updateDb = true;
                                Facebook.Rest.attachment a = new Facebook.Rest.attachment();
                                a.name = question.Title;
                                a.href = string.Format("http://stackoverflow.com/questions/{0}/", question.Id);
                                fbApi.Stream.Publish("asked a question on Stack Overflow", a, null, null, (long)item.FacebookId);
                            }

                            var answers = client.GetUsersAnswers(((int)item.StackOverflowId).ToArray(), QuestionsByUserSort.Activity, SortDirection.Descending, null, null, false, false, null, null, (DateTime)item.LastUpdate);
                            foreach (var answer in answers)
                            {
                                updateDb = true;
                                Facebook.Rest.attachment a = new Facebook.Rest.attachment();
                                a.name = answer.Title;
                                a.href = string.Format("http://stackoverflow.com/questions/{0}/{1}#{1}", answer.QuestionId, answer.Id);
                                fbApi.Stream.Publish("answered a question on Stack Overflow", a, null, null, (long)item.FacebookId);
                            }

                            if (updateDb)
                            {
                                repository.SetLastUpdate(item.AccountId, updateTime);
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                    Program.Log(ex.Message);
                }
                System.Threading.Thread.Sleep(60000);
            }
        }
    }
}
